package com.ywb.ex03;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author ywb
 */
public class Task1 extends JFrame {

    JPanel jPanel1 = new JPanel();
    JLabel label = new JLabel("");
    JLabel label2 = new JLabel("");
    JButton startButton = new JButton();
    JButton stopButton = new JButton();
    long timeCount = 0;
    MyThread thread = null;

    public Task1() {

        try {
            jbInit();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void jbInit() throws Exception {
        setTitle("计时器");
        setLocationRelativeTo(null);
        setResizable(false);
        startButton.setText("start");
        startButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                startButton_actionPerformed(e);
            }
        });
        stopButton.setText("stop");
        stopButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                stopButton_actionPerformed(e);
            }
        });
        this.getContentPane().add(jPanel1, BorderLayout.CENTER);
        jPanel1.add(startButton);
        startButton.setBounds(36, 105, 82, 30);

        jPanel1.add(stopButton);
        stopButton.setBounds(160, 108, 100, 31);

        jPanel1.add(label);
        stopButton.setBounds(40, 120, 200, 80);

        jPanel1.add(label2);
    }

    void startButton_actionPerformed(ActionEvent e) {
        if(thread != null){
            thread.stop();
        }
        thread = new MyThread();
        thread.start();
    }

    void stopButton_actionPerformed(ActionEvent e) {
        if(thread != null){
            thread.stop();
        }
        thread = null;
    }

    public static void main(String[] args) {
        Task1 test = new Task1();

        test.setSize(500, 100);

        test.show();

    }

    private class MyThread extends Thread {
        public MyThread() {
            timeCount = 0;
        }
        @Override
        public void run() {
            while(true){
                try{
                    TimeUnit.SECONDS.sleep(1);
                }catch (InterruptedException ie){
                    ie.printStackTrace();
                }
                SimpleDateFormat spf = new SimpleDateFormat("hh:mm:ss");
                Date date = new Date();
                label.setText(spf.format(date));
                label2.setText("经过了" + ++timeCount + "秒");
            }

        }
    }
}
